﻿using System.IO;
using System.Web;

namespace visinia.SmartEngine
{
    /// <summary>
    /// visinia image handler
    /// </summary>
    internal class ImageHandler : IHttpHandler
    {
        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return false; }
        }

        public void ProcessRequest(HttpContext context)
        {
            if (!string.IsNullOrEmpty(context.Request.QueryString["picture"]))
            {
                string fileName = context.Request.QueryString["picture"];                
                try
                {
                    FileInfo fi = new FileInfo(context.Server.MapPath(WebRoots.GetResourcesRoot) + fileName);
                    if (fi.Exists)
                    {                        
                        // Fix for IE not handling jpg image types
                        if (string.Compare(fi.Extension, "jpg") == 0)
                            context.Response.ContentType = "image/jpeg";
                        else
                            context.Response.ContentType = "image/" + fi.Extension.Remove(0, 1);// remove "." 
                        if (PermittedExtension(fi.Extension))
                            context.Response.TransmitFile(fi.FullName);
                    }
                    else
                        context.Response.Redirect(WebRoots.GetWebRoot + "error404.aspx");
                }
                catch
                {
                    //context.Response.End();
                }
            }
        }

        private static bool PermittedExtension(string extension)
        {
            if (string.Compare(extension, ".jpg") == 0)
                return true;
            if (string.Compare(extension, ".jpeg") == 0)
                return true;
            if (string.Compare(extension, ".gif") == 0)
                return true;
            if (string.Compare(extension, ".png") == 0)
                return true;
            if (string.Compare(extension, ".bmp") == 0)
                return true;            
            if (string.Compare(extension, ".tif") == 0)
                return true;
            if (string.Compare(extension, ".tiff") == 0)
                return true;
            return false;
        }
        #endregion
    }
}
